package de.haw.dbp.a4.gui;

import java.awt.Component;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.util.ArrayList;

import javax.swing.JFrame;
import javax.swing.UIManager;

import dc.connectionmanager.database.OracleConnectionManager;
import dc.connectionmanager.logic.IUpdaterConnStatus;
import de.haw.dbp.a4.logic.Application;
import de.haw.dbp.a4.logic.DBCommand;
import de.haw.dbp.a4.playground.JPanelSimpleSQLExecuter;
import de.haw.dbp.a4.playground.SimpleSQLExecuter;
import de.haw.global.settings.DatabaseSettings;
import javax.swing.JTabbedPane;


public class MainFrame extends JFrame 
{
	private static final long serialVersionUID = -5621099709192094317L;
	private OracleConnectionManager ocm;
        
    private JTabbedPane tab;

    private JPShowMedia showMedia;
    private JPShowAusleihe showAusleihe;
    private JPanelSimpleSQLExecuter simpleSQLExecuter;

        
	private ArrayList<Component> usedComponents;
	
	public MainFrame()
	{
		super(Application.APPNAME + " - " + Application.APPVERSION);
		
		this.setSize(800, 500);
		this.setResizable(true);
		
		try
		{
			UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
		}
		catch (Exception ex)
		{} //Nothing to do here
		
		this.usedComponents = new ArrayList<Component>();
		
		ocm = new OracleConnectionManager(DatabaseSettings.ORACLE_URL, DatabaseSettings.ORACLE_PORT, DatabaseSettings.ORACLE_USERNAME, DatabaseSettings.ORACLE_PASSWORD, DatabaseSettings.ORACLE_SID);
		ocm.registerCommandClass(new DBCommand(ocm));
		ocm.setMinConnection(1);
		ocm.setMaxConnection(3);
		ocm.setUpdaterInterval(3000);
		
		
		ocm.registerConnStatusFunc(new IUpdaterConnStatus() 
		{
			@Override
			public void handleConnectionStatus(boolean connected) 
			{
				lockGUIElements(connected);
			}
		});
                
        tab = new JTabbedPane();
        tab.setSize(this.getSize());
        tab.setLocation(0,0);

        showMedia = new JPShowMedia(this, ocm);
        showAusleihe = new JPShowAusleihe(this, ocm);
        
        simpleSQLExecuter = new JPanelSimpleSQLExecuter(this, ocm);
        usedComponents.add(simpleSQLExecuter);

        this.tab.addTab("Eingetragene Medien", showMedia);
        this.tab.addTab("Ausgeliehene Medien", showAusleihe);
        this.tab.addTab("Simple SQL Executer", simpleSQLExecuter);

        this.usedComponents.add(showAusleihe);
        this.usedComponents.add(showMedia);

        this.add(tab);
                
                
		this.addWindowListener(new WindowAdapter() 
		{
			@Override
			public void windowClosing(WindowEvent e) 
			{
				super.windowClosing(e);
				System.exit(0);
			}
		});
	}
	
	private void lockGUIElements(boolean connected)
	{	
		for(Component com : this.usedComponents)
		{
			if(com.isEnabled() != connected)
			{
				com.setEnabled(connected);
			}
		}
	}
	
	
}
